package com.ge.myoned.service.impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.RandomUtil;
import com.ge.myoned.service.TestLockService;
import com.ge.myoned.service.TestThreadService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.task.TaskExecutor;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

/**
 * @Author geqingxiang
 * @PackageName myProject
 * @Package com.ge.oned.service.impl
 * @Date 2023/6/8 15:08
 * @Version 1.0
 */
@Slf4j
@Service
public class TestThreadServiceImpl implements TestThreadService {
    @Autowired
    private TaskExecutor taskExecutor;
    @Autowired
    private TestLockService testLockService;

    @Override
    public void testOne() {
        for (int i = 0; i < 5; i++){
            taskExecutor.execute(this::doTest);
        }
        System.out.println("main thread:" + Thread.currentThread().getName());
    }

    @Async("threadPoolTaskExecutor")
    public void doTest() {
        log.info("线程：{}，开始执行:{}", Thread.currentThread().getName(),DateUtil.now());
        int c = RandomUtil.randomInt(100, 1000);
        try {
            Thread.sleep(c);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
        log.info("线程：{}，休眠时间:{}毫秒", Thread.currentThread().getName(),c);
        log.info("线程：{}，结束执行:{}", Thread.currentThread().getName(),DateUtil.now());
    }


    @Override
    public void testTwo() {
        for (int i = 0; i < 5; i++){
            taskExecutor.execute(this::doTestTwo);
        }
        System.out.println("main thread:" + Thread.currentThread().getName());
    }

    @Async("threadPoolTaskExecutor")
    public void doTestTwo() {
        log.info("线程：{}，开始执行:{}", Thread.currentThread().getName(), DateUtil.now());
        testLockService.testLockOne();
        log.info("线程：{}，结束执行:{}", Thread.currentThread().getName(),DateUtil.now());
    }
}
